package cn.acewill.yxd.yunxundian.pubClass;

import android.app.ProgressDialog;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.File;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.model.CommonMapBean;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.tempLostRR;
import cn.acewill.yxd.yunxundian.ui.MainActivity;

/**
 * Created by XXX on 2017/5/16.
 */

/*上传所有的信息*/
public class UpLoadRePort {
    protected  YXDAPP yxdapp=new YXDAPP();
    protected  DbManager db = x.getDb(yxdapp.getDaoConfig());
    private Schedule thisSch;

    private ProgressDialog dialog=null;


    private static UpLoadRePort instance=null;
    private UpLoadRePort(){
    };


    public static synchronized UpLoadRePort getInstance(Context context){
        if (instance==null){
            instance=new UpLoadRePort();
        }
        return instance;
    }

    /**
     * 此处判断是否可以进行上传的操作
     * @param context
     * @param schId 执行任务的数据id;
     *
     */
    public void upLoadCheck(Context context,int schId){
        List<tempLostRR> temp=null;
        try {
            temp = db.selector(tempLostRR.class).where("schId", "=", schId).findAll();
        }catch (DbException e) {
            e.printStackTrace();
        }
        if (temp == null||temp.size()==0) {
            new MaterialDialog.Builder(context)
                    .content("当前无数据提交，请进行添加")
                    .positiveText("确定")
                    .positiveColor(ContextCompat.getColor(context, R.color.color_theme))
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            dialog.dismiss();
                        }
                    })
                    .build()
                    .show();
        }else{

            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String currentTime=sdf.format(date);
            try {
                thisSch = db.selector(Schedule.class).where("ID","=", schId).findFirst();
                if (thisSch!=null){
                    upLoadDsOrScore(context,schId,currentTime,temp);
                }
            } catch (DbException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 此处上传用户的评论信息和评分数据
     *
     * @param schId 点击的日程id
     * @param startTime 上传的时间戳
     * @param list  执行任务的数据
     */
    public  void  upLoadDsOrScore(final Context context, final int schId, final String startTime, List<tempLostRR> list){
        JSONObject obj=new JSONObject();
        Map<String,Object> map=new HashMap<>();
        Gson gson=new Gson();
        map.put("task","getReportItemFromDevice");
        map.put("schid",schId);
        map.put("schstarttime",startTime);
        map.put("tIrrList", gson.toJson(list));
        dialog=new ProgressDialog(context);
        pubClass.setDialog(dialog);
        dialog.setMessage("正在上传数据");
        if(!dialog.isShowing()){
            dialog.show();
        }
        pubClass.Post(pubClass.Server_namehzm,map,new pubClass.MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                String[] resArry= result.split("\\|");
                if(resArry[0].equals("200")){
                    Toast.makeText(context,"数据上传成功",Toast.LENGTH_SHORT).show();
                    if(thisSch.getStates()==1||thisSch.getRealStartTime()==null)
                    {
                       /*应于数据提交成功后修改状态*/
                        try {
                            thisSch.setStates(3);
                            thisSch.setRealStartTime(startTime);
                            db.saveOrUpdate(thisSch);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    }
                    Schedule thisSch=null;
                    CommonMapBean cmb=new CommonMapBean();
                    cmb.setCmType("fenshu");
                    cmb.setServerId(schId);
                    cmb.setCmValue(resArry[3]);
                    try {
                        db.saveOrUpdate(cmb);
                        thisSch=db.selector(Schedule.class).where("ID","=",schId+"").findFirst();

                    }catch (DbException e)
                    {
                        e.printStackTrace();
                    }
                    upLoadImage(context,schId);

                }else if(resArry[0].equals("201")) {
                  Toast.makeText(context,"数据上传失败",Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                BaseActivity.showAnimaDialog(context,"网络连接错误");
                dialog.dismiss();
            }
        });
    }

    /**
     * 上传图片和视频数据
     * @param context
     * @param schId
     */
    public  void upLoadImage(final Context context, final int schId){
        int count=0;
        try {
            List<tempLostRR> rrlist = null;
            rrlist = db.selector(tempLostRR.class).where("schId", "=",schId).findAll();
            Map<String, Object> map = new HashMap<>();
            map.put("task", "getReportJpgFromDevice");
            if (rrlist!=null&&rrlist.size()>0){
            for (tempLostRR rr : rrlist) {
                String[] ss = rr.getJpgStr().split(",");
                String[] sp=rr.getVideoStr().split(",");
                for (String s : ss) {
                    //裁剪时已经进行压缩
                    File f = new File(s);
                    map.put("uploadfile"+count, f);
                    count++;
                }
                for (String p:sp){
                    File f = new File(p);
                    map.put("uploadfile"+count, f);
                    count++;
                }
            }
            dialog.setMessage("正在上传图片和视频");
            pubClass.UpLoadFile(pubClass.Server_namehzm, map, new pubClass.MyCallBack<String>() {
                @Override
                public void onSuccess(String result) {
                    super.onSuccess(result);
                    Toast.makeText(context,"图片视频上传成功",Toast.LENGTH_SHORT).show();
                    uploadsignCon(context,schId);
                    asynScheduleData(MainActivity.id);
                }
                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    super.onError(ex, isOnCallback);
                    Toast.makeText(context,"图片视频上传失败",Toast.LENGTH_SHORT).show();
                    uploadsignCon(context,schId);
                }
            });
            }
            else{
                //没照片就不上传，进行签名上传
                dialog.dismiss();
                uploadsignCon(context,schId);
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    /**
     * 此处上传用户的签字数据
     * @param schId
     */
    public  void uploadsignCon(final Context context, int schId){
        try {
            CommonMapBean cmb = new CommonMapBean();
            cmb = db.selector(CommonMapBean.class).where("CmType", "=", "门店签名")
                    .and("IndexNum", "=", schId + "")
                    .findFirst();
            if(cmb!=null) {
                Map<String, Object> map = new HashMap<>();
                map.put("task", "getsignconFromDevice");
                map.put("schid", schId + "");
                File f = new File(cmb.getCmValue().toString());
                map.put("uploadfile", f);
                dialog.setMessage("正在上传签名");
                pubClass.UpLoadFile(pubClass.Server_namehzm, map, new pubClass.MyCallBack<String>() {
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);
                        Toast.makeText(context,"签名上传成功",Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);
                        dialog.dismiss();
                        Toast.makeText(context,"签名上传失败",Toast.LENGTH_SHORT).show();
                    }
                });
            }else{
                dialog.dismiss();
            }

        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    /**
     * 刷新数据
     * @param employeeid
     * @return
     */
    public  int asynScheduleData(int employeeid) {
        Map<String,Object> map=new HashMap<>();
        map.put("task","loadScheduleByEmpId");
        map.put("empid",String.valueOf(employeeid));
        pubClass.Post(pubClass.Server_namehzm,map,new pubClass.MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                asynScheduleData(result);
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
        return 0;
    }

    private  void asynScheduleData(String result) {
        String[] resArry = result.split("\\|");
        if (resArry[0].equals("200")) {
            Gson gson = new Gson();
            //UserInfo user=gson.fromJson(strings[0],UserInfo.class);
            Type typeList = new TypeToken<ArrayList<Schedule>>() {
            }.getType();
            ArrayList<Schedule> Schedules = gson.fromJson(pubClass.convertToArrayJson(result), typeList);
            for (Schedule ee : Schedules
                    ) {
                try {
                    Schedule dbSch = db.selector(Schedule.class).where("ID", "=", String.valueOf(ee.getID())).findFirst();
                    if (dbSch != null)//如果服务器端的任务已经是先于本地端 则更新本地数据。
                    {
                        if (ee.getStates() > dbSch.getStates()) {
                            ee.set_ID(dbSch.get_ID());
                            db.saveOrUpdate(ee);
                        }
                    } else
                        db.saveOrUpdate(ee);
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
